<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !applicationDetailsInfo.visible &&
        !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :queryMoreJson="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slipSelectRequest="slipSelectRequest"
          :clearType="clearType"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-export>
            <el-button :disabled="!canExport" @click="exportSelect"
              >出库</el-button
            >
          </template>
          <template v-slot:filter-retract>
            <el-button :disabled="!canRetract" @click="retractSelect"
              >撤回</el-button
            >
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-applicationOrderNo="scope">
          <span
            class="slip-edit"
            v-if="$permission('useReturnExportApplication:details')"
            @click="showApplicationDetail(scope.row)"
            >{{ scope.row.applicationOrderNo }}</span
          >
          <span v-else>{{ scope.row.applicationOrderNoo }}</span>
        </template>
        <template v-slot:col-sourceDeptName="scope">
          <span>{{ scope.row.useApplication.sourceDeptName }}</span>
        </template>
      </table-container>
    </div>
    <!-- 明细 -->
    <export-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      :id="detailInfo.id"
      :order-no="detailInfo.orderNo"
      @returnBack="getList"
    />
    <use-application-details
      v-if="applicationDetailsInfo.visible"
      v-model:visible="applicationDetailsInfo.visible"
      :title="applicationDetailsInfo.title"
      :id="applicationDetailsInfo.id"
      @returnModify="getList"
    />
    <DetailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></DetailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :searchList="filterInfo.searchList"
      :fieldList="tableInfo.fieldList"
      :customizeUserVO="filterInfo.query.customizeUserVO"
      :groupLevelShow="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:formData="advancedSearchInfo.data"
      :fieldList="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <export-modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :id="modifyInfo.id"
      @returnModify="getList"
    />
  </div>
</template>

<script setup name="useReturnExport">
import {
  exportUseReturnExportStatus,
  getUseReturnExportCustomizeList,
  revokeUseReturnExportStatus,
} from '@/api/use.js'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import ExportDetail from './details'
import UseApplicationDetails from './../application/details'
import ExportModify from './modify'
import DetailList from './detailList'
import { ElMessageBox } from 'element-plus'

const { proxy } = getCurrentInstance()

// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {
      depotIdAuth: {
        asTbName: 'use_return_export_order',
        columnName: 'export_depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    customizeUserVO: {},
    queryParams: {
      //status: [1, 2, 3],
    },
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'slot',
      value: 'export',
      show: proxy.$permission('useReturnExportApplication:export'),
    },
    {
      type: 'slot',
      value: 'retract',
      show: proxy.$permission('useReturnExportApplication:retract'),
    },
  ],
})
const time = ref([])
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '出库',
        event: exportHandle,
        show: proxy.$permission('useReturnExportApplication:export'),
        ifRender(row) {
          return row.status === 2
        },
      },
      // {
      //   label: "修改",
      //   event: editExport,
      //   show: proxy.$permission("useReturnExportApplication:update"),
      //   ifRender(row) {
      //     return row.status === 2;
      //   }
      // },
      // {
      //   label: "删除",
      //   event: remove,
      //   show: proxy.$permission("useReturnExportApplication:del"),
      //   ifRender(row) {
      //     return row.status === 2;
      //   }
      // },
      {
        label: '撤回',
        event: retractExport,
        show: proxy.$permission('useReturnExportApplication:retract'),
        ifRender(row) {
          return row.status === 1
        },
      },
      // {
      //   label: "取消",
      //   event: remove,
      //   show: proxy.$permission("useReturnExportApplication:cancel"),
      //   ifRender(row) {
      //     return row.status === 2;
      //   }
      // }
    ],
  },
})
const selectRows = ref([])
const detailInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const applicationDetailsInfo = ref({
  visible: false,
  id: '',
})
const modifyInfo = ref({
  visible: false,
  title: '',
  id: '',
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const detailListInfo = ref({
  visible: false,
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)

const canExport = computed(() => {
  return (
    selectRows.value.filter((item) => item.status !== 2).length === 0 &&
    selectRows.value.length > 0
  )
})
const canRetract = computed(() => {
  return (
    selectRows.value.filter((item) => item.status !== 1).length === 0 &&
    selectRows.value.length > 0
  )
})

watch(
  () => applicationDetailsInfo.value.visible,
  (value) => {
    if (!value) {
      getList()
    }
  }
)
watch(
  () => detailInfo.value.visible,
  (value) => {
    if (!value) {
      getList()
    }
  }
)
watch(
  () => filterInfo.value.query.exportTimeGreater,
  (value) => {
    if (!value) {
      time.value = null
    }
  }
)

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'useReturnExport' && el.url === val.url) {
                detailInfo.value.visible = false
                modifyInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.orderNo = val.orderNo
                    detailInfo.value.id = val.orderId
                    sessionStorage.setItem('storeRowId', val.orderId)
                    console.log(detailInfo.value, 11111111)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

setData()
function setData() {
  let obj = {
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'use_return_export_status',
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  let _filterInfo = filterInfo.value
  let arr = [
    {
      asTbName: 'use_return_export_order',
      columnName: 'export_depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  _filterInfo.query.queryMap = {}
  _filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  _filterInfo.query.queryMap = proxy.$fn.deepClone(_filterInfo.copyQueryMap)
}
// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
// 明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.value.id = row.id
  detailInfo.value.orderNo = row.orderNo
  detailInfo.value.visible = true
}
function showApplicationDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  applicationDetailsInfo.value.id = row.applicationOrderId
  applicationDetailsInfo.value.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      selectRows.value = data
      filterInfo.value.list[1].disabled = !selectRows.value.length
      break
  }
}
function applicatoncallback() {
  getList()
}
//出库
function exportHandle(row) {
  let param = []
  param.push(row.id)
  exportUseReturnExportStatus(param).then((res) => {
    if (res.success) {
      getList()
    }
  })
}
//批量出库
function exportSelect() {
  if (selectRows.value.length != 0) {
    let exportData = []
    let firstStatus = 2
    let isOnly = true
    selectRows.value.forEach((row) => {
      if (firstStatus != row.status) {
        isOnly = false
        return
      }
      exportData.push(row.id)
    })
    if (!isOnly) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '只能选择状态为待出库的数据',
      })
      return
    }
    ElMessageBox.confirm('此操作将更新数据, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        exportUseReturnExportStatus(exportData).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
      .catch((e) => {})
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择一条操作数据',
    })
  }
}

function retractExport(row = undefined) {
  if (row.status != 1) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前数据状态无法撤回',
    })
    return
  }
  ElMessageBox.confirm('此操作将更新数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      let ids = []
      ids.push(row.id)
      revokeUseReturnExportStatus(ids).then((res) => {
        if (res.success) {
          getList()
        }
      })
    })
    .catch((e) => {})
}
function retractSelect() {
  if (selectRows.value.length != 0) {
    let exportData = []
    let firstStatus = 1
    let isOnly = true
    selectRows.value.forEach((row) => {
      if (firstStatus != row.status) {
        isOnly = false
        return
      }
      exportData.push(row.id)
    })
    if (!isOnly) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        showClose: true,
        message: '只能选择状态为待入库的数据',
      })
      return
    }
    revokeUseReturnExportStatus(exportData).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请选择一条操作数据',
    })
  }
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.value.query.exportTimeGreater = val[0]
    filterInfo.value.query.exportTimeLess = val[1]
  } else {
    filterInfo.value.query.exportTimeGreater = ''
    filterInfo.value.query.exportTimeLess = ''
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let _tableInfo = tableInfo.value
  let _filterInfo = filterInfo.value
  let param = {
    tableKey:
      'useReturnExportOrderIndex-com.slip.spd.entity.vo.use.UseReturnExportOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      _tableInfo.fieldList = proxy.$fn.setFieldList(
        _tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        _filterInfo.searchList,
        data.detail
      )
      _filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ..._filterInfo.query.queryMap,
      }
      _filterInfo.searchList = searchInfo.searchList
      _filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      _tableInfo.api = getUseReturnExportCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  let _filterInfo = filterInfo.value
  if (_filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, _filterInfo.sortArr)
    _filterInfo.sortArr = arr
    _filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
//修改
function editExport(row) {
  modifyInfo.value.id = row.id
  modifyInfo.value.visible = true
  modifyInfo.value.title = '修改出库单'
  filterInfo.value.copyQuery = filterInfo.value.query
}
</script>

<style scoped></style>
